package com.yc.store.biz;

import com.yc.store.bean.Goods;
import com.yc.store.mapper.BillItemMapper;
import com.yc.store.mapper.GoodsMapper;
import com.yc.store.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/4/25
 * Email haijunzhou@hnit.edu.cn
 */
@Service
public class GoodsBiz {

    @Autowired
    GoodsMapper goodsMapper;

    @Transactional(rollbackFor = BizExeption.class)
    public void create(Goods goods) throws BizExeption {
        Utils.check(Utils.isEmpty(goods.getName()),"请输入名称!");
        Utils.check(Utils.isEmpty(goods.getType()),"请输入类型!");
        Utils.check(goods.getName().length()<2,"名称至少2个字符!");
        Utils.check(goods.getPrice()<=0,"金额必须大于0!");
        Utils.check(goodsMapper.countByName(goods.getName())>0,"该商品已经录入!");
        goodsMapper.insert(goods);
    }

    @Autowired
    BillItemMapper billItemMapper;
    @Transactional(rollbackFor = BizExeption.class)
    public void remove(int id){
        if (billItemMapper.countByGid(id)>0) {
            // 逻辑删除
            goodsMapper.removeById(id);
        } else {
            // 物理删除
            goodsMapper.deleteById(id);
        }
    }

    @Transactional(rollbackFor = BizExeption.class)
    public void updateGoods(Goods goods) throws BizExeption {
        Utils.check(Utils.isEmpty(goods.getName()),"商品名不能为空");
        Utils.check(goods.getName().length()<2,"名称至少2个字符!");
        Utils.check(Utils.isEmpty(goods.getType()),"商品类型不能为空");
        Utils.check(Utils.isEmpty(goods.getNums()),"商品数量不合理");
        Utils.check(goods.getNums()<0,"商品数量不合理");
        Utils.check(goods.getPrice()<0,"商品价格不合理");

        //接下来判断有没有重名的商品
        int count = goodsMapper.countByNameExceptSelf(goods);
        if(count>0){
            throw new BizExeption("不能有重名商品");
        }

        goodsMapper.updateGoods(goods);
    }
}
